package cn.com.yusys.yusp.admin.service;

import cn.com.yusys.yusp.admin.repository.mapper.AdminSmOrgMapper;
import cn.com.yusys.yusp.admin.repository.mapper.AdminSmRoleMapper;
import cn.com.yusys.yusp.commons.mapper.QueryModel;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RoleProviderService {	
	
	@Autowired
	private AdminSmRoleMapper adminSmRoleMapper;
	@Autowired
	private AdminSmOrgMapper adminSmOrgMapper;
	
	/**
     * @函数名称:findRolesByOrgIds
     * @函数描述:查询多个机构角色
     * @参数与返回说明:
     * @算法描述:
     */
	public List<Map<String,Object>> findRolesByOrgIds(QueryModel model) {
		
		String orgIds = (String) model.getCondition().get("orgIds");
		List<String> orgInList = new ArrayList<String>();
		Map<String,List<String>> paramMap = new HashMap<String,List<String>>();
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();

		//如果机构字符串不为空则查询所选择参数
		if(orgIds!= null && !"".equals(orgIds)) {
			String[] orgStr = orgIds.split(",");
			for(int a=0;a<orgStr.length;a++) {
				orgInList.add(orgStr[a]);
			}
			//格式,orgId,orgId
			List<Map<String,String>> orgList = this.adminSmOrgMapper.getParentOrgIds(orgInList);
			
			if(orgList!= null && orgList.size()>0) {
				List<String> orgParam = new ArrayList<String>();
				for(int b=0;b<orgList.size();b++) {
					String orgs = orgList.get(b).get("orgSeq");
					if(!"".equals(orgs)) {
						String[] str = orgs.split(",");
						for(int c=0;c<str.length;c++) {
							if(!"".equals(str[c])&&!"NULL".equals(str[c]))
							orgParam.add(str[c]);
						}
					}
				}
				paramMap.put("ids", orgParam);
				// 设置分页查询参数(设置到线程变量中了)
				PageHelper.startPage(model.getPage(), model.getSize());
				list = this.adminSmRoleMapper.findAllByOrgIds(paramMap);
				// 清除线程绑定的分页参数，防止影响同线程的其他查询			
				PageHelper.clearPage();
				
			}
			
		}
		//如果机构字符串为空，则直接查询所有角色
		else {
			paramMap.put("ids", null);
			// 设置分页查询参数(设置到线程变量中了)
			PageHelper.startPage(model.getPage(), model.getSize());
			list = this.adminSmRoleMapper.findAllByOrgIds(paramMap);
			// 清除线程绑定的分页参数，防止影响同线程的其他查询
			PageHelper.clearPage();
		}
	 		
		return list;
	}
}